<template>
  <a-layout class="home">
    <a-layout-sider width="250" style="background: #fff; box-shadow: 2px 0 6px rgba(0, 21, 41, 0.35);">
      <div class="logo">列表</div>
      <a-menu
          v-model:selectedKeys="selectedKeys2"
          v-model:openKeys="openKeys"
          mode="inline"
          :style="{ height: '100%', borderRight: 0 }"
          @click="handleMenuClick"
      >
        <template v-for="item in categories" :key="item.id">
          <a-sub-menu>
            <template #title>
              <span>
                <BookTwoTone />
                {{ item.name }}
              </span>
            </template>
            <a-menu-item v-for="child in item.children" :key="child.id">{{ child.name }}</a-menu-item>
          </a-sub-menu>
        </template>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header style="background: #fff; padding: 0 24px; box-shadow: 0 2px 8px #f0f1f2;">
        <h1 style="color: #1890ff; margin: 0;">Lee的知识库</h1>
      </a-layout-header>
      <a-layout-content :style="{ padding: '24px', minHeight: '280px' }">
        <div v-if="!selectedKeys2.length" class="intro">
          <a-result>
            <template #icon>
              <TrophyTwoTone />
            </template>
            <template #title>
              欢迎使用 知识库
              管理员账号: liy
              密码: 1
            </template>
            <template #subTitle>
              请从左侧菜单选择一个分类开始探索吧
            </template>
          </a-result>
        </div>
        <a-empty v-else-if="!showDocContent && !showEbookList" description="该分类下暂无电子书" />
        <div v-else-if="!showDocContent && showEbookList" class="ebook-list">
          <a-list item-layout="vertical" size="large" :data-source="ebooks" :grid="{ gutter: 20, column: 4 }">
            <template #renderItem="{ item }">
              <a-list-item key="item.name" class="custom-list-item">
                <a-list-item-meta :description="item.description">
                  <template #title>
                    <a href="javascript:;">{{ item.name }}</a>
                  </template>
                  <template #avatar>
                    <FolderTwoTone :style="{ fontSize: '32px' }" />
                  </template>
                </a-list-item-meta>
                <div class="item-actions">
                  <a-button type="primary" @click="viewEbookDocs(item.id)">查看文档</a-button>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
        <div v-else-if="showDocContent && !showDocDetail" class="doc-list">
          <a-button type="primary" @click="goBackToEbookList" ghost>
            <template #icon><ArrowLeftOutlined /></template>
            返回电子书列表
          </a-button>
          <a-divider />
          <h2 class="doc-list-title">文档列表</h2>
          <a-tree
              v-if="ebookDocs.length > 0"
              :tree-data="ebookDocs"
              :field-names="fieldNames"
              :selectable="false"
              block
              default-expand-all
              class="custom-tree"
          >
            <template #title="{ name, id }">
              <a @click="viewDocDetail(id)">{{ name }}</a>
            </template>
          </a-tree>
          <a-empty v-else description="该电子书下暂无文档" />
        </div>
        <div v-else class="doc-detail">
          <a-page-header
              :title="currentDoc.name"
              sub-title="文档详情"
              @back="goBackToDocList"
          />
          <a-card class="custom-card">
            <div class="doc-content" v-html="currentDoc.content"></div>
          </a-card>
        </div>
      </a-layout-content>

    </a-layout>

    <!-- Login Modal -->
    <a-modal v-model:visible="showLoginModal" title="登录" @ok="handleLogin" @cancel="showLoginModal = false">
      <a-form>
        <a-form-item label="用户名">
          <a-input v-model:value="loginForm.username" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input v-model:value="loginForm.password" type="password" />
        </a-form-item>
      </a-form>
      <p v-if="loginError" style="color: red;">{{ loginError }}</p>
    </a-modal>
  </a-layout>
</template>


<script lang="ts">
import { defineComponent, onMounted, ref, watch } from 'vue';
import axios from "axios";
import { ArrowLeftOutlined, FolderTwoTone, BookTwoTone, TrophyTwoTone } from "@ant-design/icons-vue";
import { useStore } from 'vuex';


export default defineComponent({
  setup() {
    const store = useStore();
    const selectedKeys2 = ref<string[]>([]);
    const openKeys = ref<string[]>([]);
    const categories = ref([]);
    const ebooks = ref([]);
    const ebookDocs = ref([]);
    const currentDoc = ref({});
    const showEbookList = ref(false);
    const showDocContent = ref(false);
    const showDocDetail = ref(false);
    const showLoginModal = ref(false);
    const loginForm = ref({ username: '', password: '' });
    const loginError = ref<string | null>(null);

    const fieldNames = {
      children: 'children',
      title: 'name',
      key: 'id',
    };

    const handleMenuClick = ({ key }: { key: string }) => {
      const category2Id = parseInt(key);
      fetchEbooksByCategory(category2Id);
      showEbookList.value = true;
      showDocContent.value = false;
      showDocDetail.value = false;
    };

    const fetchEbooksByCategory = async (category2Id: number) => {
      try {
        const response = await axios.get(`/ebook/list/category`, {
          params: {
            category2Id: category2Id
          }
        });
        ebooks.value = response.data.content.list;
      } catch (error) {
        console.error('Failed to fetch ebooks by category:', error);
      }
    };

    const viewEbookDocs = async (ebookId: number) => {
      try {
        const response = await axios.get(`/doc/all?ebookId=${ebookId}`);
        ebookDocs.value = response.data.content;
        showDocContent.value = true;
        showDocDetail.value = false;
      } catch (error) {
        console.error('Failed to fetch ebook docs:', error);
      }
    };

    const viewDocDetail = async (docId: number) => {
      try {
        const response = await axios.get(`/doc/document/content`, {
          params: {
            id: docId
          }
        });
        currentDoc.value = response.data.content;
        showDocDetail.value = true;
      } catch (error) {
        console.error('Failed to fetch doc detail:', error);
      }
    };

    const goBackToEbookList = () => {
      showDocContent.value = false;
      showDocDetail.value = false;
    };

    const goBackToDocList = () => {
      showDocDetail.value = false;
    };

    const handleLogin = async () => {
      try {
        const response = await axios.post(`/login`, {
          username: loginForm.value.username,
          password: loginForm.value.password,
        });
        if (response.data.success) {
          store.dispatch('updateToken', response.data.token);
          showLoginModal.value = false;
          loginError.value = null;
        } else {
          loginError.value = response.data.content;
        }
      } catch (error) {
        loginError.value = '登录失败,请重试';
        console.error('Login failed:', error);
      }
    };

    watch(selectedKeys2, (newValue) => {
      if (newValue.length === 0) {
        showEbookList.value = false;
        showDocContent.value = false;
        showDocDetail.value = false;
      }
    });

    onMounted(() => {
      axios.get(`/category/all`)
          .then((response) => {
            if (response.data && response.data.content) {
              categories.value = response.data.content;
            }
          })
          .catch((error) => {
            console.error("数据获取失败:", error);
          });
    });

    return {
      selectedKeys2,
      openKeys,
      categories,
      ebooks,
      ebookDocs,
      currentDoc,
      showEbookList,
      showDocContent,
      showDocDetail,
      showLoginModal,
      loginForm,
      loginError,
      fieldNames,
      handleMenuClick,
      viewEbookDocs,
      viewDocDetail,
      goBackToEbookList,
      goBackToDocList,
      handleLogin,
      TrophyTwoTone
    };
  },
  components: {
    ArrowLeftOutlined,
    FolderTwoTone,
    BookTwoTone,
    TrophyTwoTone
  }
});
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Bangers&display=swap');

.home {
  min-height: 100vh;
}

.logo {
  height: 32px;
  background: rgba(255, 255, 255, 0.3);
  margin: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #1890ff;
  font-weight: bold;
}

.intro {
  text-align: center;
  padding: 24px;
}

.ebook-list, .doc-list, .doc-detail {
  background-color: #fff;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 2px 8px #f0f1f2;
}

:deep(.ant-tree-node-content-wrapper) {
  display: inline-block;
  width: calc(100% - 24px);
  padding-left: 4px;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.3s;
}

:deep(.ant-tree-node-content-wrapper):hover {
  background-color: #e6f7ff;
}

.doc-content {
  line-height: 1.8;
  font-size: 16px;
  color: #595959;
}

.custom-list-item {
  padding: 16px;
  border-radius: 4px;
  transition: box-shadow 0.3s, transform 0.3s;
  background: linear-gradient(135deg, #f9f9f9, #ffffff);
}

.custom-list-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.custom-list-item .ant-list-item-meta-title a {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.custom-list-item .ant-list-item-meta-description {
  color: #666;
  font-size: 14px;
  margin-top: 4px;
}

.item-actions {
  text-align: right;
  margin-top: auto;
}

.item-actions .ant-btn-primary {
  background: #1890ff;
  border-color: #1890ff;
}

.item-actions .ant-btn-primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

/* Custom styles for the tree component */
.custom-tree :deep(.ant-tree-treenode-selected) {
  background-color: #bae7ff !important;
  border-radius: 4px;
}

.custom-tree :deep(.ant-tree-treenode-selected .ant-tree-title) {
  color: #0050b3 !important;
}

.custom-tree :deep(.ant-tree-title) {
  transition: color 0.3s;
}

.custom-tree :deep(.ant-tree-title:hover) {
  color: #1890ff !important;
}

.custom-card {
  transition: transform 0.3s, box-shadow 0.3s;
}

.custom-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.custom-card .ant-card-body {
  padding: 24px;
}

.doc-list {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.doc-list .ant-tree {
  background: transparent;
}

.doc-list .ant-tree-node-content-wrapper {
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.doc-list .ant-tree-node-content-wrapper:hover {
  background-color: rgba(24, 144, 255, 0.1);
}

.doc-list .ant-tree-title {
  font-size: 16px;
  color: #333;
  transition: color 0.3s;
}

.doc-list .ant-tree-title:hover {
  color: #1890ff;
}

.doc-list .ant-tree-iconEle {
  color: #1890ff;
}

.doc-list-title {
  font-family: 'Bangers', cursive;
  font-size: 24px;
  color: #1890ff;
  margin-bottom: 16px;
}
</style>
